import 'package:flutter/material.dart';
import 'package:flutter_deer/account/account_router.dart';
import 'package:flutter_deer/account/iview/user_bank_iview.dart';
import 'package:flutter_deer/account/models/bank_entity.dart';
import 'package:flutter_deer/account/presenter/user_bank_presenter.dart';
import 'package:flutter_deer/account/provider/user_bank_provider.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/mvp/power_presenter.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/routers/fluro_navigator.dart';
import 'package:flutter_deer/util/change_notifier_manage.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/widgets/my_app_bar.dart';
import 'package:flutter_deer/widgets/my_button.dart';
import 'package:flutter_deer/widgets/my_scroll_view.dart';
import 'package:flutter_deer/widgets/selected_item.dart';
import 'package:flutter_deer/widgets/text_field_item.dart';
import 'package:flutter_deer/account/models/user_bank_entity.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:provider/provider.dart';

class AddWithdrawalAccountPage extends StatefulWidget {

  const AddWithdrawalAccountPage({super.key});

  @override
  _AddWithdrawalAccountPageState createState() => _AddWithdrawalAccountPageState();
}

class _AddWithdrawalAccountPageState extends State<AddWithdrawalAccountPage> with BasePageMixin<AddWithdrawalAccountPage, PowerPresenter<dynamic>>, AutomaticKeepAliveClientMixin<AddWithdrawalAccountPage>,ChangeNotifierMixin<AddWithdrawalAccountPage> implements UserBankIMvpView {
  bool _isWechat = false;
  String _bank = '';
  String _bankId = '';

  final TextEditingController _cardUsernameController = TextEditingController();
  final TextEditingController _cardNoController = TextEditingController();
  final FocusNode _nodeText1 = FocusNode();
  final FocusNode _nodeText2 = FocusNode();
  UserBankProvider provider = UserBankProvider();
  bool _clickable = false;
  @override
  bool get wantKeepAlive => true;
  late UserBankPagePresenter userBankPagePresenter;

  @override
  PowerPresenter<dynamic> createPresenter() {
    final PowerPresenter<dynamic> powerPresenter = PowerPresenter<dynamic>(this);
    userBankPagePresenter = new UserBankPagePresenter();
    powerPresenter.requestPresenter([userBankPagePresenter]);
    return powerPresenter;
  }

  List<String> _indexBarData = <String>[];

  @override
  void saveUserBankSuccess(){
    NavigatorUtils.goBackWithParams(context, 'add');
  }

  @override
  void saveUserBankFail(){

  }

  @override
  void removeUserBankSuccess() {

  }

  @override
  void setUserBankList(List<UserBankEntity>? userBankList){
    provider.setUserBankList(userBankList);
  }

  void _verify() {
    bool clickable = true;
    String? cardUsername = _cardUsernameController.text.nullSafe;
    if(cardUsername.isEmpty){
      clickable = false;
    }
    String? cardNo = _cardNoController.text.nullSafe;
    if(cardNo.isEmpty){
      clickable = false;
    }
    if(_bankId==null||_bankId==0){
      clickable = false;
    }
    if (clickable != _clickable) {
      setState(() {
        _clickable = clickable;
      });
    }
  }

  @override
  Map<ChangeNotifier, List<VoidCallback>?>? changeNotifier() {
    final List<VoidCallback> callbacks = <VoidCallback>[_verify];
    return <ChangeNotifier, List<VoidCallback>?>{
      _cardUsernameController: callbacks,
      _cardNoController: callbacks,
      _nodeText1: null,
      _nodeText2: null,
    };
  }
  
  @override
  Widget build(BuildContext context) {
    final TextStyle? style = Theme.of(context).textTheme.titleSmall?.copyWith(fontSize: Dimens.font_sp14);
    final List<Widget> children = <Widget>[
      Gaps.vGap5,
      Visibility(
        maintainState: true, /// 是为了保留填写信息，其实就是Offstage，这里只是展示另一种方法。
        visible: !_isWechat,
        child: Column(
          children: <Widget>[
            TextFieldItem(
              controller: _cardUsernameController,
              title: '${DeerLocalizations.of(context)!.cardholder.nullSafe}',
              hintText: '${DeerLocalizations.of(context)!.cardholderTip.nullSafe}',
              focusNode: _nodeText1,
            ),
            TextFieldItem(
              title: '${DeerLocalizations.of(context)!.bankCardNumber.nullSafe}',
              keyboardType: TextInputType.number,
              hintText: '${DeerLocalizations.of(context)!.bankCardNumberTip.nullSafe}',
              focusNode: _nodeText2,
              controller: _cardNoController,
            ),
            SelectedItem(
              title: '${DeerLocalizations.of(context)!.bankName.nullSafe}',
              content: _bank.isEmpty ? '${DeerLocalizations.of(context)!.chooseBank.nullSafe}' : _bank,
              style: _bank.isEmpty ? style : null,
              onTap: () {
                NavigatorUtils.pushResult(context, '${AccountRouter.bankSelectPage}?type=0', (Object result) {
                  setState(() {
                    if(result!=null) {
                      final BankEntity model = result as BankEntity;
                      _bank = model.name.nullSafe;
                      _bankId = model.id ?? '';
                      _verify();
                    }
                  });
                });
              },
            ),
          ],
        ),
      ),
      Padding(
        padding: const EdgeInsets.only(top: 8.0, left: 16.0),
        child: Text(
          _isWechat ? '${DeerLocalizations.of(context)!.bindLoginWeChatAccountOnMachine.nullSafe}' : '${DeerLocalizations.of(context)!.bindCardholderCard.nullSafe}',
          style: Theme.of(context).textTheme.titleSmall,
        ),
      ),
    ];
    return ChangeNotifierProvider<UserBankProvider>(
      create: (_) => provider,
      child:Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: MyAppBar(
          title: '${DeerLocalizations.of(context)!.addAccount.nullSafe}',
        ),
        body: MyScrollView(
            bottomButton: Padding(
                padding: EdgeInsets.only(left: 16.0, right: 16.0, bottom: 8.0),
                child: Consumer<UserBankProvider>(
                    builder: (_,provider,child){
                      return  MyButton(
                        onPressed: _clickable?_submit:null,
                        text: '${DeerLocalizations.of(context)!.ok.nullSafe}',
                      );
                    }
                )
            ),
            children: children
        ),
      )
    );
  }

  void _submit() {
    userBankPagePresenter.saveUserBank(_bankId, _cardNoController.text.nullSafe, _cardUsernameController.text.nullSafe);
  }

  void _dialogSelect(bool flag) {
    setState(() {
      _isWechat = flag;
    });
    NavigatorUtils.goBack(context);
  }

  @override
  void initState() {
    super.initState();
    // userBankPagePresenter.fetchUserBankList();
  }

  @override
  void dispose() {
    provider.dispose();
    _cardNoController.dispose();
    _cardUsernameController.dispose();
    super.dispose();
  }
}
